#include "normal_algo.h"

/**
 * @brief 从位图中提取文本框
 * @param pred 预测图
 * @param bitmap 二值化图
 * @param final_resize_h 最终调整的高度
 * @param final_resize_w 最终调整的宽度
 * @param info 加密信息
 * @param unit 检测单元
 */
void BoxesFromBitmap(
	const cv::Mat pred, 
    const cv::Mat bitmap,
    const int& final_resize_h, 
    const int& final_resize_w,
    st_encrypt_info_ovino & info, 
    st_detect_unit & unit) 
{
	const int min_size = 3;
	const int max_candidates = 1000;

	int width = bitmap.cols;
	int height = bitmap.rows;

	std::vector<std::vector<cv::Point>> contours;
	std::vector<cv::Vec4i> hierarchy;

	cv::findContours(bitmap, contours, hierarchy, cv::RETR_LIST,
		cv::CHAIN_APPROX_SIMPLE);

	int num_contours =
		contours.size() >= max_candidates ? max_candidates : contours.size();

	std::string det_db_score_mode = info.mode;

	std::vector<std::vector<std::vector<int>>> boxes;
	std::vector<float> v_box_prob;

	for (int _i = 0; _i < num_contours; _i++) {
		
		if (contours[_i].size() <= 2) {
			continue;
		}
		float ssid;
		cv::RotatedRect box = cv::minAreaRect(contours[_i]);
		auto array = GetMiniBoxes(box, ssid);

		auto box_for_unclip = array;
		// end get_mini_box

		if (ssid < min_size) {
			continue;
		}
		float score;
		if (det_db_score_mode == "slow")
			/* compute using polygon*/
			score = PolygonScoreAcc(contours[_i], pred);
		else
			score = BoxScoreFast(array, pred);

// 		if (score < info.box_threshold)
// 			continue;
		if (score < unit.param.prob_thres)
			continue;

		// start for unclip
		cv::RotatedRect points = UnClip(box_for_unclip, info.unclip_ratio);
		if (points.size.height < 1.001 && points.size.width < 1.001) {
			continue;
		}
		// end for unclip

		cv::RotatedRect clipbox = points;
		auto cliparray = GetMiniBoxes(clipbox, ssid);

		if (ssid < min_size + 2)
			continue;

		int dest_width = pred.cols;
		int dest_height = pred.rows;
		std::vector<std::vector<int>> intcliparray;
		for (int num_pt = 0; num_pt < 4; num_pt++)
		{
			std::vector<int> a{ int(clampf(roundf(cliparray[num_pt][0] / float(width) *
												 float(dest_width)),
										  0, float(dest_width))),
							   int(clampf(roundf(cliparray[num_pt][1] /
												 float(height) * float(dest_height)),
										  0, float(dest_height))) };
			intcliparray.push_back(a);
		}
		boxes.push_back(intcliparray);
		v_box_prob.push_back(score);

	} // end for
	
	float ratio_h = float(final_resize_h) / float(unit.img.h);
	float ratio_w = float(final_resize_w) / float(unit.img.w);
	boxes = FilterTagDetRes(boxes, v_box_prob, ratio_h, ratio_w, unit.img);

	for (auto i = 0; i < v_box_prob.size(); ++i)
	{
		if (i >= BOX_MAX_NUM)
		{
			break;
		}
		//std::cout << "ploygon id: i: " << i << std::endl;

		st_box& box = unit.result.boxes[i];
		box.prob = v_box_prob[i];
		box.polygon.node_num = 4;
		
		unit.result.vaild_num = i + 1;

		for (int num_pt = 0; num_pt < 4; num_pt++)
		{
			//std::cout << " node id :" << num_pt << " x: " << boxes[i][num_pt][0] << " y: " << boxes[i][num_pt][1] << std::endl;

			box.polygon.pts[num_pt].x = boxes[i][num_pt][0];
			box.polygon.pts[num_pt].y = boxes[i][num_pt][1];
		}
	}
}

/**
 * @brief 获取最小外接矩形的四个顶点坐标
 * @param box 旋转矩形
 * @param ssid 输出矩形的最大边长
 * @return 返回按顺序排列的四个顶点坐标
 */
std::vector<std::vector<float>> GetMiniBoxes(cv::RotatedRect box, float& ssid) {
	ssid = __max(box.size.width, box.size.height);

	cv::Mat points;
	cv::boxPoints(box, points);

	auto array = Mat2Vector(points);
	std::sort(array.begin(), array.end(), XsortFp32);

	std::vector<float> idx1 = array[0], idx2 = array[1], idx3 = array[2],
		idx4 = array[3];
	if (array[3][1] <= array[2][1]) {
		idx2 = array[3];
		idx3 = array[2];
	}
	else {
		idx2 = array[2];
		idx3 = array[3];
	}
	if (array[1][1] <= array[0][1]) {
		idx1 = array[1];
		idx4 = array[0];
	}
	else {
		idx1 = array[0];
		idx4 = array[1];
	}

	array[0] = idx1;
	array[1] = idx2;
	array[2] = idx3;
	array[3] = idx4;

	return array;
}

/**
 * @brief 将OpenCV的Mat转换为vector
 * @param mat 输入Mat矩阵
 * @return 转换后的二维vector
 */
std::vector<std::vector<float>> Mat2Vector(cv::Mat mat) {
	std::vector<std::vector<float>> img_vec;
	std::vector<float> tmp;

	for (int i = 0; i < mat.rows; ++i) {
		tmp.clear();
		for (int j = 0; j < mat.cols; ++j) {
			tmp.push_back(mat.at<float>(i, j));
		}
		img_vec.push_back(tmp);
	}
	return img_vec;
}

/**
 * @brief 浮点数向量按x坐标排序
 * @param a 第一个向量
 * @param b 第二个向量
 * @return 如果a[0]<b[0]返回true
 */
bool XsortFp32(std::vector<float> a, std::vector<float> b) {
	if (a[0] != b[0])
		return a[0] < b[0];
	return false;
}

/**
 * @brief 整数向量按x坐标排序
 * @param a 第一个向量
 * @param b 第二个向量
 * @return 如果a[0]<b[0]返回true
 */
bool XsortInt(std::vector<int> a, std::vector<int> b) {
	if (a[0] != b[0])
		return a[0] < b[0];
	return false;
}

/**
 * @brief 计算轮廓面积和扩张距离
 * @param box 输入框的四个顶点坐标
 * @param unclip_ratio 扩张比例
 * @param distance 输出的扩张距离
 */
void GetContourArea(const std::vector<std::vector<float>>& box,
	float unclip_ratio, float& distance) {
	int pts_num = 4;
	float area = 0.0f;
	float dist = 0.0f;
	for (int i = 0; i < pts_num; i++) {
		area += box[i][0] * box[(i + 1) % pts_num][1] -
			box[i][1] * box[(i + 1) % pts_num][0];
		dist += sqrtf((box[i][0] - box[(i + 1) % pts_num][0]) *
			(box[i][0] - box[(i + 1) % pts_num][0]) +
			(box[i][1] - box[(i + 1) % pts_num][1]) *
			(box[i][1] - box[(i + 1) % pts_num][1]));
	}
	area = fabs(float(area / 2.0));

	distance = area * unclip_ratio / dist;
}

/**
 * @brief 对文本框进行扩张
 * @param box 输入框的四个顶点坐标
 * @param unclip_ratio 扩张比例
 * @return 扩张后的旋转矩形
 */
cv::RotatedRect UnClip(std::vector<std::vector<float>> box,
	const float& unclip_ratio) {
	float distance = 1.0;

	GetContourArea(box, unclip_ratio, distance);

	ClipperLib::ClipperOffset offset;
	ClipperLib::Path p;
	p << ClipperLib::IntPoint(int(box[0][0]), int(box[0][1]))
		<< ClipperLib::IntPoint(int(box[1][0]), int(box[1][1]))
		<< ClipperLib::IntPoint(int(box[2][0]), int(box[2][1]))
		<< ClipperLib::IntPoint(int(box[3][0]), int(box[3][1]));
	offset.AddPath(p, ClipperLib::jtRound, ClipperLib::etClosedPolygon);

	ClipperLib::Paths soln;
	offset.Execute(soln, distance);
	std::vector<cv::Point2f> points;

	for (int j = 0; j < soln.size(); j++) {
		for (int i = 0; i < soln[soln.size() - 1].size(); i++) {
			points.emplace_back(soln[j][i].X, soln[j][i].Y);
		}
	}
	cv::RotatedRect res;
	if (points.size() <= 0) {
		res = cv::RotatedRect(cv::Point2f(0, 0), cv::Size2f(1, 1), 0);
	}
	else {
		res = cv::minAreaRect(points);
	}
	return res;
}

/**
 * @brief 计算多边形区域的平均得分
 * @param contour 轮廓点集
 * @param pred 预测图
 * @return 区域的平均得分
 */
float PolygonScoreAcc(std::vector<cv::Point> contour,
	cv::Mat pred) {
	int width = pred.cols;
	int height = pred.rows;
	std::vector<float> box_x;
	std::vector<float> box_y;
	for (int i = 0; i < contour.size(); ++i) {
		box_x.push_back(contour[i].x);
		box_y.push_back(contour[i].y);
	}

	int xmin =
		clamp(int(std::floor(*(std::min_element(box_x.begin(), box_x.end())))), 0,
			width - 1);
	int xmax =
		clamp(int(std::ceil(*(std::max_element(box_x.begin(), box_x.end())))), 0,
			width - 1);
	int ymin =
		clamp(int(std::floor(*(std::min_element(box_y.begin(), box_y.end())))), 0,
			height - 1);
	int ymax =
		clamp(int(std::ceil(*(std::max_element(box_y.begin(), box_y.end())))), 0,
			height - 1);

	cv::Mat mask;
	mask = cv::Mat::zeros(ymax - ymin + 1, xmax - xmin + 1, CV_8UC1);

	cv::Point* rook_point = new cv::Point[contour.size()];

	for (int i = 0; i < contour.size(); ++i) {
		rook_point[i] = cv::Point(int(box_x[i]) - xmin, int(box_y[i]) - ymin);
	}
	const cv::Point* ppt[1] = { rook_point };
	int npt[] = { int(contour.size()) };

	cv::fillPoly(mask, ppt, npt, 1, cv::Scalar(1));

	cv::Mat croppedImg;
	pred(cv::Rect(xmin, ymin, xmax - xmin + 1, ymax - ymin + 1))
		.copyTo(croppedImg);
	float score = cv::mean(croppedImg, mask)[0];

	delete[] rook_point;
	return score;
}

/**
 * @brief 快速计算框的得分
 * @param box_array 框的四个顶点坐标
 * @param pred 预测图
 * @return 框的平均得分
 */
float BoxScoreFast(std::vector<std::vector<float>> box_array,
	cv::Mat pred) {
	auto array = box_array;
	int width = pred.cols;
	int height = pred.rows;

	float box_x[4] = { array[0][0], array[1][0], array[2][0], array[3][0] };
	float box_y[4] = { array[0][1], array[1][1], array[2][1], array[3][1] };

	int xmin = clamp(int(std::floor(*(std::min_element(box_x, box_x + 4)))), 0,
		width - 1);
	int xmax = clamp(int(std::ceil(*(std::max_element(box_x, box_x + 4)))), 0,
		width - 1);
	int ymin = clamp(int(std::floor(*(std::min_element(box_y, box_y + 4)))), 0,
		height - 1);
	int ymax = clamp(int(std::ceil(*(std::max_element(box_y, box_y + 4)))), 0,
		height - 1);

	cv::Mat mask;
	mask = cv::Mat::zeros(ymax - ymin + 1, xmax - xmin + 1, CV_8UC1);

	cv::Point root_point[4];
	root_point[0] = cv::Point(int(array[0][0]) - xmin, int(array[0][1]) - ymin);
	root_point[1] = cv::Point(int(array[1][0]) - xmin, int(array[1][1]) - ymin);
	root_point[2] = cv::Point(int(array[2][0]) - xmin, int(array[2][1]) - ymin);
	root_point[3] = cv::Point(int(array[3][0]) - xmin, int(array[3][1]) - ymin);
	const cv::Point* ppt[1] = { root_point };
	int npt[] = { 4 };
	cv::fillPoly(mask, ppt, npt, 1, cv::Scalar(1));

	cv::Mat croppedImg;
	pred(cv::Rect(xmin, ymin, xmax - xmin + 1, ymax - ymin + 1))
		.copyTo(croppedImg);

	auto score = cv::mean(croppedImg, mask)[0];
	return score;
}

/**
 * @brief 过滤检测结果
 * @param boxes 检测框集合
 * @param v_box_prob 检测框得分
 * @param ratio_h 高度比例
 * @param ratio_w 宽度比例
 * @param srcimg 原始图像
 * @return 过滤后的检测框集合
 */
std::vector<std::vector<std::vector<int>>> FilterTagDetRes(
	std::vector<std::vector<std::vector<int>>> boxes, std::vector<float> & v_box_prob, float ratio_h,
	float ratio_w, st_img_rgb & srcimg) {
	int oriimg_h = srcimg.h;
	int oriimg_w = srcimg.w;

	std::vector<std::vector<std::vector<int>>> root_points;
	std::vector<float> _v_box_prob;

	for (int n = 0; n < boxes.size(); n++) {
		boxes[n] = OrderPointsClockwise(boxes[n]);
		for (int m = 0; m < boxes[0].size(); m++) {
			boxes[n][m][0] /= ratio_w;
			boxes[n][m][1] /= ratio_h;

			boxes[n][m][0] = int(__min(__max(boxes[n][m][0], 0), oriimg_w - 1));
			boxes[n][m][1] = int(__min(__max(boxes[n][m][1], 0), oriimg_h - 1));
		}
	}

	for (int n = 0; n < boxes.size(); n++) {
		int rect_width, rect_height;
		rect_width = int(sqrt(pow(boxes[n][0][0] - boxes[n][1][0], 2) +
			pow(boxes[n][0][1] - boxes[n][1][1], 2)));
		rect_height = int(sqrt(pow(boxes[n][0][0] - boxes[n][3][0], 2) +
			pow(boxes[n][0][1] - boxes[n][3][1], 2)));
		if (rect_width <= 4 || rect_height <= 4)
			continue;
		root_points.push_back(boxes[n]);
		_v_box_prob.push_back(v_box_prob[n]);
	}
	v_box_prob = _v_box_prob;
	return root_points;
}

/**
 * @brief 将点集按顺时针方向排序
 * @param pts 输入点集
 * @return 排序后的点集
 */
std::vector<std::vector<int>> OrderPointsClockwise(std::vector<std::vector<int>> pts) {
	std::vector<std::vector<int>> box = pts;
	std::sort(box.begin(), box.end(), XsortInt);

	std::vector<std::vector<int>> leftmost = { box[0], box[1] };
	std::vector<std::vector<int>> rightmost = { box[2], box[3] };

	if (leftmost[0][1] > leftmost[1][1])
		std::swap(leftmost[0], leftmost[1]);

	if (rightmost[0][1] > rightmost[1][1])
		std::swap(rightmost[0], rightmost[1]);

	std::vector<std::vector<int>> rect = { leftmost[0], rightmost[0], rightmost[1],
										  leftmost[1] };
	return rect;
}

/**
 * @brief 获取旋转裁剪后的图像
 * @param srcimage 原始图像
 * @param box 裁剪框的四个顶点坐标
 * @return 裁剪后的图像
 */
cv::Mat GetRotateCropImage(const cv::Mat& srcimage,
	std::vector<std::vector<int>> box) {
	cv::Mat image;
	srcimage.copyTo(image);
	std::vector<std::vector<int>> points = box;

	int x_collect[4] = { box[0][0], box[1][0], box[2][0], box[3][0] };
	int y_collect[4] = { box[0][1], box[1][1], box[2][1], box[3][1] };
	int left = int(*std::min_element(x_collect, x_collect + 4));
	int right = int(*std::max_element(x_collect, x_collect + 4));
	int top = int(*std::min_element(y_collect, y_collect + 4));
	int bottom = int(*std::max_element(y_collect, y_collect + 4));

	cv::Mat img_crop;
	image(cv::Rect(left, top, right - left, bottom - top)).copyTo(img_crop);

	for (int i = 0; i < points.size(); i++) {
		points[i][0] -= left;
		points[i][1] -= top;
	}

	int img_crop_width = int(sqrt(pow(points[0][0] - points[1][0], 2) +
		pow(points[0][1] - points[1][1], 2)));
	int img_crop_height = int(sqrt(pow(points[0][0] - points[3][0], 2) +
		pow(points[0][1] - points[3][1], 2)));

	cv::Point2f pts_std[4];
	pts_std[0] = cv::Point2f(0., 0.);
	pts_std[1] = cv::Point2f(img_crop_width, 0.);
	pts_std[2] = cv::Point2f(img_crop_width, img_crop_height);
	pts_std[3] = cv::Point2f(0.f, img_crop_height);

	cv::Point2f pointsf[4];
	pointsf[0] = cv::Point2f(points[0][0], points[0][1]);
	pointsf[1] = cv::Point2f(points[1][0], points[1][1]);
	pointsf[2] = cv::Point2f(points[2][0], points[2][1]);
	pointsf[3] = cv::Point2f(points[3][0], points[3][1]);

	cv::Mat M = cv::getPerspectiveTransform(pointsf, pts_std);

	cv::Mat dst_img;
	cv::warpPerspective(img_crop, dst_img, M,
		cv::Size(img_crop_width, img_crop_height),
		cv::BORDER_REPLICATE);

	if (float(dst_img.rows) >= float(dst_img.cols) * 1.5) {
		cv::Mat srcCopy = cv::Mat(dst_img.rows, dst_img.cols, dst_img.depth());
		cv::transpose(dst_img, srcCopy);
		cv::flip(srcCopy, srcCopy, 0);
		return srcCopy;
	}
	else {
		return dst_img;
	}
}